﻿using System;
using System.IO;
using System.Text;

namespace Fly.Serializers
{
    /// <summary>
    /// XML 序列化
    /// </summary>
    public static class XmlSerializer
    {
        #region Functions

        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <param name="obj">Object to serialize</param>
        /// <param name="encoding"></param>
        /// <returns>The serialized object</returns>
        public static string Serialize(object obj,Encoding encoding = null)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            if (encoding == null)
            {
                encoding = new UTF8Encoding(false);
            }
            using (MemoryStream stream = new MemoryStream())
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
                serializer.Serialize(stream, obj);
                stream.Flush();
                return encoding.GetString(stream.GetBuffer(), 0, (int)stream.Position);
            }
        }

        /// <summary>
        /// 反序列化对象
        /// </summary>
        /// <param name="objectType">Object type</param>
        /// <param name="data">Data to deserialize</param>
        /// <param name="encoding"></param>
        /// <returns>The resulting object</returns>
        public static object Deserialize(string data, Type objectType, Encoding encoding = null)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                return null;
            }
            if (encoding == null)
            {
                encoding = new UTF8Encoding(false);
            }
            using (MemoryStream stream = new MemoryStream(encoding.GetBytes(data)))
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(objectType);
                return serializer.Deserialize(stream);
            }
        }

        #endregion
    }
}
